package org.dingfugui.triple.serialize.jdk;

import org.dingfugui.triple.serialize.Serialize;

import java.io.*;

/**
 * 序列化的jdk实现
 * 要求被序列化对象实现Serializable接口
 * Created by fugui.ding on 2015/3/22.
 */
public class JdkSerialize implements Serialize {
    @Override
    public byte[] serialize(Object obj) throws IOException {
        try (ByteArrayOutputStream abos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(abos)) {
            oos.writeObject(obj);
            return abos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public Object deserialize(byte[] data) throws Exception {

        try (ObjectInputStream oos = new ObjectInputStream(new ByteArrayInputStream(data))) {
            return oos.readObject();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw e;
        }
    }

}
